﻿using Ldt.DataEngine.RuleAssemble;
using LdtDataEngin.ModuleDetail.BaseModule;
using LdtJudge.DataEngine.Data;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace LdtDataEngin.ModuleDetail.CommonModule.CommonCapacity
{
    /// <summary>
    /// 争议焦点处理
    /// </summary>
    public class ArgumentFocusHandle: AssermBase
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public ArgumentFocusHandle()
        {
            Sqlsyscommon = new SqlSysCommon("");
        }
        /// <summary>
        /// 系统库通用处理类
        /// </summary>
        public SqlSysCommon Sqlsyscommon { get; }

        /// <summary>
        /// 获取争议焦点
        /// MSCourtRecord
        /// </summary>
        /// <param name="orignalText">原文</param>
        /// <param name="causeid">案由ID</param>
        /// <param name="sourceName">文书编号</param>
        /// <param name="paragraphCode">逻辑段编号</param>
        /// <param name="message">争议焦点匹配返回消息</param>
        /// <returns>争议焦点 其中key表示争议焦点CC_ID，value 表示争议焦点表述</returns>
        public Dictionary<string, string> GetArgumentFocus(string orignalText, string causeid, string sourceName, string paragraphCode, out string message)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (string.IsNullOrWhiteSpace(causeid))
            {
                message = " Error, 案由ID不能为空！";
                return result;
            }
            if (string.IsNullOrWhiteSpace(sourceName))
            {
                message = " Error, 文书ID不能为空！";
                return result;
            }
            if (string.IsNullOrWhiteSpace(paragraphCode))
            {
                message = " Error, 文书段落不能为空！";
                return result;
            }
            try
            {
                //获取所有关联的信息单元 获取CC_NodeType=16 表示争议焦点，CC_NodeType=15 争议焦点分类
                //string strsql = @"SELECT
                //                             b.CC_Name,
                //                             [ES_ID],
                //                             b.[CC_ID],
                //                             [Source_ID],
                //                             [Source_ParagraphID],
                //                             [Source_Name],
                //                             [Source_ParagraphName],
                //                             t.[CC_RegexInfoCode],
                //                             [IsParagraphExtract],
                //                             [IsEvidenceMatch]
                //                            FROM
                //                             Ldt_JudgeDocSystem.dbo.[SYS_Express_Source] t
                //                            LEFT JOIN Ldt_JudgeDocSystem.dbo.SYS_CaseCause b ON t.CC_ID = b.CC_ID
                //                            WHERE 
                //                                b.CC_NodeType=16 AND
                //                             t.Source_ID = '" + sourceName + "' AND t.Source_ParagraphID = '" + paragraphCode + "' AND b.AllParentId LIKE '%," + causeid + ",%'";
                //DataTable dt=Sqlsyscommon.GetDataTable(strsql);
                IFreeSql freeSql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("Ldt_JudgeDocSystem");
                var listmo = freeSql.Select<SYS_Express_Source, SYS_CaseCause>().LeftJoin((t, b) => t.CC_ID == b.CC_ID).Where((t, b) => b.CC_NodeType == 16 &&

                                                     t.Source_ID == sourceName && t.Source_ParagraphID == paragraphCode && b.AllParentId.Contains("," + causeid + ",")).ToList((t, b) => new
                                                     {
                                                         b.CC_Name,
                                                         t.ES_ID,
                                                         b.CC_ID,
                                                         t.Source_ID,
                                                         t.Source_ParagraphID,
                                                         t.Source_Name,
                                                         t.Source_ParagraphName,
                                                         t.CC_RegexInfoCode,
                                                         t.IsParagraphExtract,
                                                         t.IsEvidenceMatch
                                                     });


                DataTable dt = ObjectToTable(listmo);
                //逐个信息单元比对
                foreach (DataRow dr in dt.Rows)
                {
                    string riu_id = RuleParseClass.GetRIU_ID(dr["CC_RegexInfoCode"].ToString());
                    bool reslutismatch = RuleParseClass.IsMatch(riu_id, orignalText);

                    if (reslutismatch && !result.ContainsKey(dr["CC_ID"].ToString()))
                    {
                        result.Add(dr["CC_ID"].ToString(), dr["CC_Name"].ToString());
                    }
                }
                if (result.Count > 0)
                {
                    message = "Success,成功匹配到争议焦点！";
                }
                else
                {
                    message = "Success,未能匹配到符合内容的争议焦点！";
                }
            }
            catch (Exception err)
            {
                message = "Error, 争议焦点匹配失败！错误消息为：" + err.Message;
            }
            return result;
        }

        /// <summary>
        /// 将对象转换为datatable 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="selectModels"></param>
        /// <returns></returns>
        private DataTable ObjectToTable<T>(List<T> selectModels)
        {
            DataTable dt = new DataTable();
            Type elementType = typeof(T);

            elementType.GetProperties().ToList().ForEach(propInfo => dt.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));

            foreach (var item in selectModels)
            {
                DataRow row = dt.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                dt.Rows.Add(row);
            }
            return dt;
        }


    }
}
